// pages/i/comment.js
const PingService = require('../../services/ping');
const auth = require('../../utils/auth');
const CdnService = require('../../services/cdn');
const BizGoodsOrderService = require('../../services/bizOrder');
const BizPayService = require('../../services/bizPay');
const OrderService = require('../../services/order');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        orderId: null,
        type:null,
        orderInfo: null,
        rating: 0, // 星级评分
        content: '', // 点评内容
        images: [], // 图片数组
        maxImages: 9, // 最大图片数量
        submitting: false, // 提交状态
        userInfo: null // 用户信息
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const { order_id,type } = options;
        if (!order_id) {
            wx.showToast({
                title: '订单ID不能为空',
                icon: 'none'
            });

            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }

        if(!type){
            wx.showToast({
                title: '点评类型不能为空',
                icon: 'none'
            });

            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
            return;
        }

        this.setData({
            orderId: order_id,
            type:type
        });

        // 检查登录状态
        this.checkLoginStatus();
    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            // 检查登录状态
            const loginStatus = await auth.checkLoginStatus();

            if (!loginStatus.isLoggedIn) {
                wx.showModal({
                    title: '提示',
                    content: '请先登录',
                    showCancel: false,
                    success: () => {
                        wx.redirectTo({
                            url: '/pages/index/login'
                        });
                    }
                });
                return;
            }

            // 检查用户信息完整性
            const userInfo = auth.getUserInfo();
            if (!auth.isValidUserInfo(userInfo)) {
                wx.showModal({
                    title: '提示',
                    content: '请先绑定手机号',
                    showCancel: false,
                    success: () => {
                        wx.redirectTo({
                            url: '/pages/index/login'
                        });
                    }
                });
                return;
            }

            this.setData({
                userInfo: userInfo
            });

            // 获取订单信息
            this.getOrderInfo();
        } catch (error) {
            wx.showModal({
                title: '提示',
                content: '登录状态检查失败，请重试',
                showCancel: false,
                success: () => {
                    wx.redirectTo({
                        url: '/pages/index/login'
                    });
                }
            });
        }
    },

    /**
     * 获取订单信息
     */
    async getOrderInfo() {
        try {
            let result = null;
            // 这里应该调用订单详情接口
            if(this.data.type == 'pay'){
                result = await BizPayService.getPayRecordDetail(this.data.orderId);
            }else if(this.data.type == 'biz-order'){
                result = await BizGoodsOrderService.getOrderDetail(this.data.orderId);
            }else if(this.data.type == 'store-order'){
                result = await OrderService.one(this.data.orderId);
            }
            
            if(result.success){
                this.setData({
                    orderInfo: result.data
                },function(){
                    if(this.data.type == 'pay'){
                        wx.setNavigationBarTitle({
                            title: result.data.biz.name
                        });
                    }else if(this.data.type == 'biz-order'){
                        wx.setNavigationBarTitle({
                            title: result.data.biz.name
                        });
                    }else if(this.data.type == 'store-order'){
                        
                    }
                });
            }

        } catch (error) {
            console.error('获取订单信息失败:', error);
        }
    },

    /**
     * 选择星级
     */
    onRatingChange(e) {
        const rating = e.detail;
        this.setData({
            rating: rating
        });
    },
    /**
     * 选择图片
     */
    chooseImage() {
        const { images, maxImages } = this.data;
        const remaining = maxImages - images.length;

        if (remaining <= 0) {
            wx.showToast({
                title: `最多只能上传${maxImages}张图片`,
                icon: 'none'
            });
            return;
        }

        wx.chooseImage({
            count: remaining,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const newImages = [...images, ...res.tempFilePaths];
                this.setData({
                    images: newImages
                });
            }
        });
    },

    /**
     * 删除图片
     */
    deleteImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = [...this.data.images];
        images.splice(index, 1);
        this.setData({
            images: images
        });
    },

    /**
     * 预览图片
     */
    previewImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = this.data.images;
        wx.previewImage({
            current: images[index],
            urls: images
        });
    },

    /**
     * 提交点评
     */
    async submitPing() {
        const { orderId, rating, content, images, submitting,type } = this.data;

        if (submitting) {
            return;
        }

        if (rating === 0) {
            wx.showToast({
                title: '请选择星级评分',
                icon: 'none'
            });
            return;
        }

        if (!content.trim()) {
            wx.showToast({
                title: '请输入点评内容',
                icon: 'none'
            });
            return;
        }

        this.setData({
            submitting: true
        });

        try {
            // 上传图片
            const uploadedImages = [];
            if (images.length > 0) {
                const cdnResult = await CdnService.getAliyunCredit();
                if(cdnResult.success){
                    wx.showLoading({
                        title: '上传图片中...'
                    });
                }

                let data = cdnResult.data;

                for (let i = 0; i < images.length; i++) {
                    try {
                        let ext = images[i].split('.').pop() || 'jpg';
                        let path = CdnService.generateFilePath('ping',ext);
                        const ossFormData = {
                            key: path,  //上传文件名称
                            policy: data.policy,   //表单域
                            'x-oss-signature-version': data.x_oss_signature_version,    //指定签名的版本和算法
                            'x-oss-credential': data.x_oss_credential,   //指明派生密钥的参数集
                            'x-oss-date': data.x_oss_date,   //请求的时间
                            'x-oss-signature': data.signature,   //签名认证描述信息
                            'x-oss-security-token': data.security_token,  //安全令牌
                            success_action_status: "200"  //上传成功后响应状态码
                        };

                        

                        const uploadResult = await this.uploadImage(images[i],ossFormData);
                        uploadedImages.push(uploadResult);
                    } catch (error) {
                        console.error('图片上传失败:', error);
                        wx.showToast({
                            title: '图片上传失败',
                            icon: 'none'
                        });
                        this.setData({
                            submitting: false
                        });
                        wx.hideLoading();
                        return;
                    }
                }

                wx.hideLoading();
            }

            // 提交点评
            const result = await PingService.submitPing({
                order_id: orderId,
                type:this.data.type,
                rating: rating,
                content: content.trim(),
                images: uploadedImages,
                showLoading: true
            });

            console.log(result);

            if (result.success) {
                wx.showToast({
                    title: '点评提交成功',
                    icon: 'success'
                });

                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                wx.showToast({
                    title: result.message,
                    icon: 'none'
                });
            }
        } catch (error) {
            console.error('提交点评失败:', error);
            wx.showToast({
                title: '提交失败，请重试',
                icon: 'none'
            });
        } finally {
            this.setData({
                submitting: false
            });
        }
    },

    /**
     * 上传图片
     */
    uploadImage(filePath,ossFormData) {
        return new Promise((resolve, reject) => {
            let url = 'https://cloud--score-static.oss-cn-beijing.aliyuncs.com';
            wx.uploadFile({
                url, // 替换为实际的上传接口
                filePath: filePath,
                name: 'file',
                formData: ossFormData,
                success: (res) => {
                    try {
                        if(res.statusCode == 200 && res.errMsg == 'uploadFile:ok'){
                            resolve(ossFormData.key);
                        }else{
                            reject(new Error(res.errMsg));
                        }
                    } catch (error) {
                        reject(new Error('上传失败'));
                    }
                },
                fail: (error) => {
                    reject(error);
                }
            });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})